package com.cavy.platform.server.controller;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.service.AgentSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author 唐旭
 * @Date 2018/7/24
 */
@ServerEndpoint("/message/{agentId}")
@Component
@Slf4j
public class AgentSessionHandler {

    @Autowired
    private AgentSessionService service = BeansProvider.getBean(AgentSessionService.class);

    @OnOpen
    public void onOpen(Session session, @PathParam("agentId") String agentId) {
        log.debug("open session:{},sid:{}", session, agentId);
        service.addAgent(session, agentId);
    }

    @OnClose
    public void onClose(Session session, @PathParam("agentId") String agentId) throws IOException {
        log.debug("onClose session:{},sid:{}", session, agentId);
        service.removeAgent(session, agentId);
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("agentId") String agentId) throws IOException {
        log.debug("onMessage session:{},sid:{},message:{}", session, agentId, message);
        service.handlerMessage(session, agentId, message);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("agentId") String agentId) throws IOException {
        log.debug("onError session:{},sid:{},error:{}", session, agentId, error);
        log.warn(error.getMessage());
    }
}
